<template>
  <div class="app-container">
    <el-card class="basic-info">
      <div slot="header">企业资料</div>
      <h4>基本信息</h4>
      <div>
        <el-form
          ref="formQyZlRef"
          :rules="rules"
          :model="enterpriseList"
          label-width="80px"
        >
          <el-form-item label="企业名称" prop="companyname">
            <el-input
              v-model="enterpriseList.companyname"
              placeholder=""
              disabled
              style="width: 35%"
            ></el-input>
          </el-form-item>
          <el-form-item label="企业性质" prop="nature">
            <el-select
              v-model="enterpriseList.nature"
              placeholder="民营"
              style="width: 35%"
            >
              <el-option
                v-for="item in enterpriseXzList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业规模" prop="scale">
            <el-select
              v-model="enterpriseList.scale"
              placeholder="请选择企业规模"
              style="width: 35%"
            >
              <el-option
                v-for="item in enterpriseGmList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属行业" prop="trade">
            <el-select
              v-model="enterpriseList.trade"
              placeholder="机械/设备重工"
              style="width: 35%"
            >
              <el-option
                v-for="item in enterpriseHyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册资金" prop="registered">
            <el-input
              v-model="enterpriseList.registered"
              placeholder="请输入内容"
              style="width: 35%"
            >
              <template slot="append">万人民币</template>
            </el-input>
          </el-form-item>
          <el-form-item label="企业网址" prop="website">
            <el-input
              v-model="enterpriseList.website"
              placeholder="请输入企业网址"
              style="width: 35%"
            ></el-input>
          </el-form-item>
          <el-form-item label="企业福利" prop="tags">
            <el-select
              v-model="enterpriseList.tags"
              multiple
              placeholder="请选择"
              :multiple-limit="10"
            >
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-button
              type="text"
              class="clear-btn"
              @click="clearTags"
              v-if="enterpriseList.tags && enterpriseList.tags.length"
            >
              清空
            </el-button>
          </el-form-item>
          <el-form-item label="所在地区" prop="areaLists">
            <el-cascader
              clearable
              v-model="enterpriseList.areaLists"
              :options="areaList"
              :props="{
                checkStrictly: true, // 允许选择任意一级
                emitPath: true, // 返回完整路径
                expandTrigger: 'hover', // 悬停展开
              }"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="企业地址" prop="address">
            <el-input
              v-model="enterpriseList.address"
              placeholder=""
              style="width: 25%"
            ></el-input>
          </el-form-item>
          <el-form-item label="企业介绍" prop="content">
            <el-input
              v-model="enterpriseList.content"
              placeholder=""
              type="textarea"
              :rows="7"
              style="width: 50%"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 上传营业执照/法人证书 -->

      <div class="logo-uploader">
        <el-upload
          action="#"
          :http-request="handlelicenseChange"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="licenseFileList"
          :on-change="handleLicenseChange"
          :limit="1"
          :class="{ 'hide-upload': hideUpload }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div>
          <div style="text-align: center; margin-top: 10px; color: #5da3fd">
            上传营业执照/法人证书
          </div>

          <div class="upload-tip">
            <i class="el-icon-info"></i>
            建议尺寸：240*165
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <div slot="header">联系方式</div>
      <div style="margin-top: 30px">
        <el-form
          ref="formQyZlRef"
          :model="enterpriseList"
          :rules="rules"
          label-width="80px"
        >
          <!-- <el-form-item label="联系方式" prop="useCompanyContact">
            <el-select
              v-model="enterpriseList.useCompanyContact"
              placeholder="请选择"
              style="width: 35%"
            >
              <el-option label="使用企业资料联系方式" :value="1"></el-option>
              <el-option label="使用其他联系方式" :value="2"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="联系人" prop="contact">
            <el-input
              v-model="enterpriseList.contact"
              placeholder=""
              style="width: 35%"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="mobile">
            <el-input
              v-model="enterpriseList.mobile"
              placeholder=""
              style="width: 35%"
            ></el-input>
            <el-checkbox
              @change="handleIsSecrecy"
              v-model="enterpriseList.isSecrecy"
              label="不对外显示仅接受通知"
              style="margin-left: 10px"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="联系微信" prop="weixin">
            <el-input
              v-model="enterpriseList.weixin"
              placeholder=""
              style="width: 35%"
            ></el-input>
            <el-checkbox
              v-model="enterpriseList.weixinSameAsMobile"
              label="同手机号"
              style="margin-left: 10px"
              @change="handleWeixinSameAsMobile"
            ></el-checkbox>
          </el-form-item>
          <el-form-item label="联系固话" prop="telephone">
            <el-input
              v-model="enterpriseList.telephone"
              placeholder="请输入联系固话(格式:区区号+电话号)"
              style="width: 35%"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">
            <el-input
              v-model="enterpriseList.email"
              placeholder="请输入联系邮箱"
              style="width: 35%"
            ></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" style="width: 258px" @click="btnClick"
              >保存</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  queryEnterpriseDataApi,
  selCategoryDistrictListApi,
  selCategoryNatureListApi,
  selCategoryScaleListApi,
  selCategoryTradeListApi,
  editEnterpriseBasicInfoApi,
  addCompanyAuthApi,
  selCompanyAuthApi,
  selTagListApi,
} from "@/api/qyManage";
export default {
  data() {
    return {
      // 企业信息表单
      enterpriseList: {
        uid: "",
        cid: "",
        contact: "",
        content: "",
        district1: "",
        district2: "",
        district3: "",
        mobile: "",
        nature: "",
        scale: "",
        trade: "",
        address: "",
        email: "",
        isSecrecy: false,
        registered: "",
        tags: [],
        website: "",
        weixin: "",
        areaLists: [],
        amount: null,
        department: "",
        education: null,
        useCompanyContact: 1, // 默认使用其他联系方式
        weixinSameAsMobile: false,
      },
      // 经验要求
      experienceList: [
        { label: "不限", value: 0 },
        { label: "1年", value: 1 },
        { label: "2年", value: 2 },
        { label: "3年", value: 3 },
        { label: "3-5年", value: 4 },
        { label: "5-10年", value: 5 },
        { label: "10年以上", value: 6 },
      ],
      // 学历要求
      educationalList: [
        { label: "不限", value: 0 },
        { label: "初中", value: 1 },
        { label: "高中", value: 2 },
        { label: "中技", value: 3 },
        { label: "中专", value: 4 },
        { label: "大专", value: 5 },
        { label: "本科", value: 6 },
        { label: "硕士", value: 7 },
        { label: "博士", value: 8 },
        { label: "博士后", value: 9 },
      ],
      // 福利
      tags: [],
      // 营业执照/法人证书
      licenseForm: {
        uid: "",
        cid: "",
        file: "",
      },
      // 企业性质
      enterpriseXzList: [],
      // 企业规模
      enterpriseGmList: [],
      // 所属行业
      enterpriseHyList: [],
      // 所在地区
      areaList: [],
      districtType: [],
      // 营业执照/法人证书
      licenseFileList: [],
      rules: {
        uid: [{ required: true }],
        cid: [{ required: true }],
        contact: [
          { required: true, message: "请输入企业介绍", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入职位描述", trigger: "blur" },
        ],
        district1: [
          { required: true, message: "请选择所在地区", trigger: "change" },
        ],
        district2: [
          { required: true, message: "请选择所在地区", trigger: "change" },
        ],
        district3: [
          { required: true, message: "请选择所在地区", trigger: "change" },
        ],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        nature: [
          { required: true, message: "请选择企业性质", trigger: "change" },
        ],
        scale: [
          { required: true, message: "请选择企业规模", trigger: "change" },
        ],
        trade: [
          { required: true, message: "请选择所属行业", trigger: "change" },
        ],
      },
      logoUrl: "", // 添加 logo URL 数据
      hideUpload: false, // 初始值设为false
    };
  },
  computed: {
    ...mapGetters(["userId", "cid"]),
    selectedTags() {
      return this.tags.filter((tag) =>
        this.enterpriseList.tags.includes(tag.id)
      );
    },
  },
  async created() {
    this.licenseForm.uid = this.userId;
    this.licenseForm.cid = this.cid;
    this.enterpriseList.uid = this.userId;
    this.enterpriseList.cid = this.cid;

    // 先获取标签列表
    await this.selTagList();
    // 再获取企业数据
    await this.queryEnterpriseData();

    if (this.enterpriseList.district3 === 0) {
      this.enterpriseList.areaLists = [
        this.enterpriseList.district1,
        this.enterpriseList.district2,
      ];
    } else {
      this.enterpriseList.areaLists = [
        this.enterpriseList.district1,
        this.enterpriseList.district2,
        this.enterpriseList.district3,
      ];
    }

    this.selCategoryDistrictList();
    this.selCategoryNatureList();
    this.selCategoryScaleList();
    this.selCategoryTradeList();
    this.selCompanyAuth();
  },
  methods: {
    // 不对外显示仅接受通知
    handleIsSecrecy(val) {
      console.log(val);
      // this.enterpriseList.isSecrecy = val;
    },
    // tag列表
    async selTagList() {
      const res = await selTagListApi();
      console.log("标签列表数据:", res.data);
      this.tags = res.data;
    },
    // 上传营业执照/法人证书
    async handlelicenseChange(options) {
      const file = options.file;
      const formData = new FormData();
      formData.append("uid", this.licenseForm.uid);
      formData.append("cid", this.licenseForm.cid);
      formData.append("file", file);

      try {
        const res = await addCompanyAuthApi(formData);
        if (res.code === 1) {
          this.$message.success("上传成功");
          // 重新获取文件列表
          await this.selCompanyAuth();
        } else {
          this.$message.error("上传失败");
        }
      } catch (error) {
        console.error("上传文件失败:", error);
        this.$message.error("上传失败");
      }
    },
    // 查询营业执照/法人证书
    async selCompanyAuth() {
      const res = await selCompanyAuthApi({
        uid: this.userId,
        cid: this.cid,
      });
      console.log(res);
      if (res.code === 1) {
        this.licenseFileList = [{ url: res.data }];
        this.hideUpload = this.licenseFileList.length > 0; // 设置hideUpload标志
      }
    },
    // 渲染数据
    async queryEnterpriseData() {
      const res = await queryEnterpriseDataApi(this.userId);
      // 获取企业数据
      this.enterpriseList = res.data;

      console.log("企业数据中的tags:", res.data.tags);
      console.log("当前标签列表:", this.tags);

      // 如果有tags数据，进行名称匹配
      if (res.data.tags && res.data.tags.length > 0) {
        // 将字符串数组转换为id数组
        const matchedTags = this.tags
          .filter((tag) => {
            const isMatch = res.data.tags.includes(tag.name);
            console.log(`检查标签 ${tag.name}: ${isMatch}`);
            return isMatch;
          })
          .map((tag) => tag.id);

        console.log("匹配到的标签ID:", matchedTags);
        // 更新enterpriseList中的tags为匹配到的id数组
        this.enterpriseList.tags = matchedTags;
      }
      console.log("最终的enterpriseList.tags:", this.enterpriseList.tags);
    },
    // 企业工作地区查询
    async selCategoryDistrictList() {
      try {
        const res = await selCategoryDistrictListApi();
        this.areaList = res.data[0].map((item) => ({
          label: item.name, // 父级项的 value 设置为 name
          value: item.id,
          children: item.children
            ? item.children.map((child) => ({
                label: child.name, // 子项的 label 设置为 name
                value: child.id, // 子项的 value 设置为 id 的字符串形式
                children: child.children.map((subDistrict) => ({
                  label: subDistrict.name, // 父级项的 value 设置为 name
                  value: subDistrict.id,
                })), // 子项的 children 默认为空数组，如果需要更深层次的数据结构，可以在这里添加逻辑
              }))
            : [], // 如果没有 categoryDistricts，children 设置为空数组
        }));
      } catch (error) {
        console.error("获取地区列表失败:", error);
      }
    },
    // 企业性质查询
    async selCategoryNatureList() {
      const res = await selCategoryNatureListApi();
      this.enterpriseXzList = res.data;
    },
    // 企业规模查询
    async selCategoryScaleList() {
      const res = await selCategoryScaleListApi();
      this.enterpriseGmList = res.data;
    },
    // 企业所属行业查询
    async selCategoryTradeList() {
      const res = await selCategoryTradeListApi();
      this.enterpriseHyList = res.data;
    },
    // 所在地区改变得时候
    handleChange(value) {
      console.log(value);
      if (value && value.length > 0) {
        this.enterpriseList.district1 = value[0] || "";
        this.enterpriseList.district2 = value[1] || "";
        this.enterpriseList.district3 = value[2] || 0;
        console.log("地区选择", this.enterpriseList);
      }
    },
    // 保存
    btnClick() {
      try {
        this.$refs.formQyZlRef.validate(async (valid) => {
          if (valid) {
            console.log(this.enterpriseList);
            const res = await editEnterpriseBasicInfoApi({
              cid: Number(this.cid),
              contact: this.enterpriseList.contact,
              content: this.enterpriseList.content,
              district1: this.enterpriseList.district1,
              district2: this.enterpriseList.district2,
              district3: this.enterpriseList.district3,
              mobile: this.enterpriseList.mobile,
              nature: this.enterpriseList.nature,
              scale: this.enterpriseList.scale,
              trade: this.enterpriseList.trade,
              uid: this.enterpriseList.uid,
              address: this.enterpriseList.address,
              email: this.enterpriseList.email,
              isSecrecy: this.enterpriseList.isSecrecy ? 1 : 0,
              registered: this.enterpriseList.registered,
              telephone: this.enterpriseList.telephone,
              tags: this.enterpriseList.tags,
              website: this.enterpriseList.website,
              weixin: this.enterpriseList.weixin,
            });
            // const res=await editEnterpriseBasicInfoApi(this.enterpriseList)
            if (res.code === 1) {
              this.$message.success("修改企业资料成功!");
            } else {
              this.$message.error("修改企业资料失败");
            }
          } else {
            this.$message.error("修改企业资料失败");
          }
        });
      } catch {
        this.$message.error("修改企业资料失败");
      }
    },
    handleLogoSuccess(res, file) {
      this.logoUrl = URL.createObjectURL(file.raw);
      // 处理上传成功的逻辑
    },
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("上传文件只能是图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    handleLicenseChange(file, fileList) {
      this.licenseFileList = fileList.map((item) => item);
      this.hideUpload = fileList.length >= 1;
    },
    // 处理文件删除
    async handleRemove(file, fileList) {
      try {
        if (this.licenseFileList.includes(file)) {
          this.hideUpload = false;
          this.licenseFileList = fileList;
        }
      } catch (error) {
        console.error("删除文件失败:", error);
        this.$message.error("删除失败");
        await this.selCompanyAuth();
      }
    },
    // 清空所有标签
    clearTags() {
      this.enterpriseList.tags = [];
    },
    handleWeixinSameAsMobile(val) {
      if (val) {
        this.enterpriseList.weixin = this.enterpriseList.mobile;
      }
    },
  },
  watch: {
    "enterpriseList.mobile": {
      handler(newVal) {
        if (this.enterpriseList.weixinSameAsMobile) {
          this.enterpriseList.weixin = newVal;
        }
      },
    },
  },
};
</script>

<style scoped>
.basic-info {
  position: relative;
}

.logo-uploader {
  position: absolute;
  top: 110px;
  right: 210px;
  /* width: 150px;
  height: 150px; 
  /* border: 1px dashed #d9d9d9; */
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.hide-upload :deep(.el-upload--picture-card) {
  display: none !important; /* 添加 !important 确保样式生效 */
}

.upload-tip {
  color: #999;
  font-size: 12px;
  text-align: center;
  margin-top: 10px;
}
/* :deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card) {
  display: inline-block;
} */

/* .logo-uploader:hover {
  border-color: #409eff;
} */

.logo {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.upload-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
}

.upload-placeholder i {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-placeholder p {
  margin: 0;
  font-size: 12px;
  line-height: 1.5;
  color: #409eff;
}

.tags-container {
  display: flex;
  align-items: center;
}

.clear-btn {
  color: #409eff;
  margin-left: 10px;
}

:deep(.el-select) {
  width: 35%;
}

:deep(.el-tag) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
